<?php

namespace App\V3\V3_2_7\Services;
use App\V3\V3_2_7\Models\AdminAddendumModel;
use App\V3\V3_2_7\Models\VipOrderModel;
use App\V3\V3_2_7\Models\VipSettingModel;
use  App\V3\V3_2_7\Models\AdminModel;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\DB;
use App\V3\V3_2_7\Models\StorageSpaceOrderModel;
use App\V3\V3_2_7\Models\BuyStorageSpaceModel;
class StorageSpaceOrderService
{
    public static function generateSn(){
        $date = Carbon::now('Asia/Shanghai');
        $rnd = rand(100000,999999);
        return $date->format('YmdHisu').$rnd;
    }

    public static function getWechatConfig()
    {
        return [
            'app_id' => env('MINIAPP_ID'),
            'mch_id' => env('WECHATMCH_ID'),
            'key' => env('WECHATKEY'),
            'notify_url' => 'https://'.$_SERVER['SERVER_NAME'].'/v3.0/api/wechat_order_notify_storage',
            //'sanbox' => true //沙箱模式打开或关闭
        ];
    }

    public static function getVipSetting($id)
    {
        return VipSettingModel::select('open_vip_cost')
        ->where([
            'id' => $id,
        ])->first();
    }

    public static function payByWechat($mainId,$order_sn,$data)
    {
        $order = StorageSpaceOrderModel::where([
            'order_sn' => $order_sn
        ])->first();

        if(empty($order)){
            return ['code' => 1, 'msg' => '订单创建失败', 'data' => ''];
        }

        switch ($order['type']){
            case 1:
                $body = 'VIP充值';
                break;
            case 2:
                $body = '购买存储空间';
                break;
            default:
                return ['code' => 1, 'msg' => '订单错误', 'data' => ''];
        }

        $total_fee = $order['price']*100;

        if(!empty($data['code'])){
            $wxinfo = json_decode(LoginService::getOpenId($data['code']), true);
            $open_id = $wxinfo['openid'];
        }else{
            $admin = AdminModel::select('openid')->where('id', $mainId)->first();
            $open_id = $admin['openid'];
        }

        $payment = Factory::payment(self::getWechatConfig());

        $jssdk = $payment->jssdk;

        $res = $payment->order->unify([
            'app_id' => env('WECHATAPPID'),
            'body' => $body,
            'out_trade_no' => $order_sn,
            'total_fee' => $total_fee,
            'trade_type' => 'JSAPI',
            'openid' => $open_id,
            'notify_url' => 'https://'.$_SERVER['SERVER_NAME'].'/v3.0/api/wechat_order_notify_storage',
        ]);

        if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
            $prepay_id = $res['prepay_id'];

            switch ($data['pay_type']){
                case 1:
                    //小程序
                    $config = $jssdk->sdkConfig($prepay_id);
                    #$config = $jssdk->bridgeConfig($prepay_id); //json形式
                    break;
                case 2:
                    //app
                    $config = $jssdk->appConfig($prepay_id);
                    break;
                default:
                    $config = $jssdk->sdkConfig($prepay_id);
            }
            return ['code' => 0, 'msg' => '创建订单成功', 'data' => $config];

            #$config['order_sn'] = $order_sn;
            #$config['order_id'] = $order['id'];

        }

        if($res['return_code'] == 'FAIL' && array_key_exists('return_msg',$res)){
            return ['code' => 0, 'msg' => '微信支付失败', 'data' => []];
        }

    }

    public static function createOrder($mainId,$data)
    {
        $order_sn = self::generateSn();
        $info = BuyStorageSpaceModel::select('set_space','price')->where(['id'=>$data['space_id']])->first();
        if(empty($info)) return ['code'=>1,'msg'=>'没有找到，要购买的空间选项','data'=>''];
        StorageSpaceOrderModel::updateOrCreate([
        'order_sn' => $order_sn,
        ],[
        'order_sn' => $order_sn,
        'main_id' => $mainId,
        'price' => $info['price'],
        'buy_storage_space' => $info['set_space'],
        'pay_type' => $data['pay_type'],

        ]);
        //微信支付
        if(in_array($data['pay_type'],[1,2])){
            $res = self::payByWechat($mainId,$order_sn,$data);
        }

        return $res;
    }

    //订单回调
    public static function notifyByWeChat($fields)
    {
        $config = self::getWechatConfig();
        //        // 根据返回的订单号查询订单数据
        //        $order = VipOrderModel::where('order_sn', $fields['out_trade_no'])->get()->toArray();
        //        if (!$order) {
        //            die('订单不存在!');
        //        }
        //        $order = reset($order);
        //
        //        if ($order['status'] == '1') {
        //            return true;
        //        }
        //
        //        $order['order_sn'] = $fields['out_trade_no']; // 回调订单号
        //        $order['out_order_sn'] = $fields['transaction_id']; // 回调流水号
        //        $order['pay_time'] = time();
        //        $order['status'] = 1;
        //
        //        DB::beginTransaction();
        //
        //        try {
        //            VipOrderModel::updateOrCreate([
        //                'order_sn' => $order['order_sn'],
        //            ],$order);
        //            self::updateAddendum($order['main_id'],$order);
        //
        //            DB::commit();
        //        } catch (\Exception $e) {
        //            DB::rollBack();
        //        }
        //
        //        return true;

        $payment = Factory::payment($config);

        $response = $payment->handlePaidNotify(function ($message, $fail) use ($fields) {
            Log::info('回调参数：', $message);
            // 根据返回的订单号查询订单数据
            $order = VipOrderModel::where('order_sn', $message['out_trade_no'])->get()->toArray();
            if (!$order) {
                $fail('订单不存在!');
            }
            $order = reset($order);

            if ($order['status'] == '1') {
                return true;
            }

            // 支付成功后的业务逻辑
            if ($message['result_code'] === 'SUCCESS') {
                Log::info('支付成功 开始操作数据库');

                $order['order_sn'] = $message['out_trade_no']; // 回调订单号
                $order['out_order_sn'] = $message['transaction_id']; // 回调流水号
                $order['pay_time'] = time();
                $order['status'] = 1;

                DB::beginTransaction();

                try {
                    Log::info('开始更新订单表');

                    VipOrderModel::updateOrCreate([
                        'order_sn' => $order['order_sn'],
                    ],$order);

                    #VipOrderModel::where('order_sn', $order['order_sn'])->update($order);
                    Log::info('开始更新admin_addendum表');
                    self::updateAddendum($order['main_id'],$order);

                    DB::commit();
                    Log::info('更新完成');

                    return true;
                } catch (\Exception $e) {
                    Log::info('更新失败'.var_export($e->getMessage(), true));

                    DB::rollBack();
                }
            }

            return true;
        });

            return $response;
    }

    public static function updateAddendum($main_id,$order_data)
    {
        $order_type = $order_data['type'];

        $addendum_data = AdminAddendumModel::select('*')->where(['main_id' => $main_id])->first()->toArray();

        $vip_time = 365*24*3600;

        switch ($order_type){
            case 1:
                //vip
                $vip_setting_id = 2;
                $setting_data = VipSettingModel::select('*')->where(['id' => $vip_setting_id])->first()->toArray();

                if(empty($addendum_data)){
                    $vip_end_date = $order_data['pay_time'] + $vip_time;

                }else{
                    if(time() > $addendum_data['vip_end_date']){
                        //会员过期
                        $vip_end_date = $order_data['pay_time'] + $vip_time;
                    }else{
                        $vip_end_date = $addendum_data['vip_end_date'] + $vip_time;
                    }
                }
                $is_vip = 1;

                break;
            case 2:
                //购买空间
                $vip_setting_id = 3;
                $setting_data = VipSettingModel::select('*')->where(['id' => $vip_setting_id])->first()->toArray();

                $is_vip = empty($addendum_data)? 0 : $addendum_data['is_vip'];
                $vip_end_date = empty($addendum_data)? 0 : $addendum_data['vip_end_date'];

                break;
            default:
                return false;
        }

        $is_share_customer = empty($addendum_data)? 0 : $addendum_data['is_share_customer'];
        $is_set_as_supplier = empty($addendum_data)? 0 : $addendum_data['is_set_as_supplier'];

        $is_in_experience = empty($addendum_data)? 0 : $addendum_data['is_in_experience'];
        $is_end_experience = empty($addendum_data)? 0 : $addendum_data['is_end_experience'];
        $album_amount = empty($addendum_data)? 0 : $addendum_data['album_amount'] + $setting_data['album_amount'];
        $album_page_amount = empty($addendum_data)? 0 : $addendum_data['album_page_amount'] + $setting_data['album_page_amount'];
        $empty_bill_amount = empty($addendum_data)? 0 : $addendum_data['empty_bill_amount'] + $setting_data['empty_bill_amount'];
        $special_seal = empty($addendum_data)? 0 : $addendum_data['special_seal'] + $setting_data['special_seal'];
        $one_key_album_times = empty($addendum_data)? 0 : $addendum_data['one_key_album_times'] + $setting_data['one_key_album_times'];
        $express_check_times = empty($addendum_data)? 0 : $addendum_data['express_check_times'] + $setting_data['express_check_times'];
        $account_storage = empty($addendum_data)? 0 : $addendum_data['account_storage'] + $setting_data['account_storage'];
        $clear_watermark_or_not = empty($addendum_data)? 0 : $addendum_data['clear_watermark_or_not'] + $setting_data['clear_watermark_or_not'];
        $file_total_size = empty($addendum_data)? 0 : $addendum_data['file_total_size'];

        return AdminAddendumModel::updateOrCreate([
            'main_id' => $main_id,
        ],[
            'main_id' => $main_id,
            'is_share_customer' => $is_share_customer,
            'is_set_as_supplier' => $is_set_as_supplier,
            'is_vip' => $is_vip,
            'vip_end_date' => $vip_end_date,
            'is_in_experience' => $is_in_experience,
            'is_end_experience' => $is_end_experience,
            'album_amount' => $album_amount,
            'album_page_amount' => $album_page_amount,
            'empty_bill_amount' => $empty_bill_amount,
            'special_seal' => $special_seal,
            'one_key_album_times' => $one_key_album_times,
            'express_check_times' => $express_check_times,
            'account_storage' => $account_storage,
            'clear_watermark_or_not' => $clear_watermark_or_not,
            'file_total_size' => $file_total_size,
        ]);


    }

}
